package com.wwtech.epp.ui.activity.work;

import android.content.Intent;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.chad.library.adapter.base.BaseQuickAdapter;
import com.socks.library.KLog;
import com.wwtech.epp.R;
import com.wwtech.epp.application.AppConfig;
import com.wwtech.epp.entity.ProjectEntity;
import com.wwtech.epp.entity.eventbus.Addstar;
import com.wwtech.epp.entity.eventbus.DeletProject;
import com.wwtech.epp.entity.eventbus.FinishProject;
import com.wwtech.epp.ui.activity.base.MyBaseFragment;
import com.wwtech.epp.ui.activity.work.component.DaggerProjectListComponent;
import com.wwtech.epp.ui.activity.work.contract.ProjectListContract;
import com.wwtech.epp.ui.activity.work.module.ProjectListModule;
import com.wwtech.epp.ui.activity.work.presenter.ProjectListPresenter;
import com.wwtech.epp.ui.adapter.work.ProjectListAdapter;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import javax.inject.Inject;

import butterknife.BindView;
import butterknife.ButterKnife;

/**
 * @author hzp
 * @Package com.wwtech.epp.ui.activity.work
 * @Description: $description
 * @date 2017/09/15 12:56:42
 */

public class ProjectListFragment extends MyBaseFragment implements ProjectListContract.View, SwipeRefreshLayout.OnRefreshListener,BaseQuickAdapter.RequestLoadMoreListener {

    @Inject
    ProjectListPresenter mPresenter;
    @Inject
    ProjectListAdapter projectListAdapter;

    @BindView(R.id.recyclerView)
    RecyclerView recyclerView;
    @BindView(R.id.refreshLayout)
    SwipeRefreshLayout refreshLayout;
    private String mType;
    private int mNextPage;
    private static final int ONE_PAGE_SIZE = 5;

    private int total;

    private static final String ARG_PROJECT_TYPE = "arg_project_type";

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_project_list, null);
        ButterKnife.bind(this, view);
        recyclerView.setAdapter(projectListAdapter);
        projectListAdapter.setProjectType(mType);
        refreshLayout.setOnRefreshListener(this);
        projectListAdapter.setOnLoadMoreListener(this, recyclerView);
        projectListAdapter.setOnItemClickListener(new BaseQuickAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(BaseQuickAdapter baseQuickAdapter, View view, int i) {
                Intent intent = new Intent(getActivity(), ProjectDetailActivity.class);
                intent.putExtra("projectId", projectListAdapter.getData().get(i).getProjectId());
                intent.putExtra("position", i);
                startActivity(intent);
            }
        });
        return view;
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onNewProjectSuccess(String msg) {
        if (msg.equals("refresh")) {
            if (mType.equals("我的项目") || mType.equals("参与项目"))
            loadDataFromServer(true);
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onAddStar(Addstar addstar) {
        KLog.i("收到加星标的消息");
        for (int i = 0; i < projectListAdapter.getData().size(); i++) {
            if (projectListAdapter.getData().get(i).getProjectId() == addstar.getProjectId()) {
                projectListAdapter.getData().get(i).setStar(addstar.isAdd());
                projectListAdapter.notifyDataSetChanged();
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onFinishProject(FinishProject finishProject) {
        for (int i = 0; i < projectListAdapter.getData().size(); i++) {
            if (projectListAdapter.getData().get(i).getProjectId() == finishProject.getProjectId()) {
                projectListAdapter.getData().get(i).setProjectState(1);
                projectListAdapter.notifyDataSetChanged();
            }
        }
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void onDeletProject(DeletProject deletProject) {
        for (int i = 0; i < projectListAdapter.getData().size(); i++) {
            if (projectListAdapter.getData().get(i).getProjectId() == deletProject.getProjectId()) {
                projectListAdapter.getData().remove(i);
                projectListAdapter.notifyDataSetChanged();
            }
        }
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        EventBus.getDefault().register(this);
        if (getArguments() != null) {
            mType = getArguments().getString(ARG_PROJECT_TYPE);
        }
    }

    @Override
    public void fetchData() {
        refreshLayout.post(new Runnable() {
            @Override
            public void run() {
                loadDataFromServer(true);
            }
        });
    }

    public void loadDataFromServer(boolean showRefresh) {
        refreshLayout.setRefreshing(showRefresh);
        if (showRefresh) {
            mNextPage = 1;
        }
        mPresenter.getProjectListFromServer(mType, mNextPage, ONE_PAGE_SIZE);
    }

    public static ProjectListFragment newInstance(String param) {
        ProjectListFragment fragment = new ProjectListFragment();
        Bundle args = new Bundle();
        args.putString(ARG_PROJECT_TYPE, param);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    protected void setupFragmentComponent() {
        DaggerProjectListComponent
                .builder()
                .appComponent(((AppConfig) getActivity().getApplication()).getApplicationComponent())
                .projectListModule(new ProjectListModule(this))
                .build()
                .inject(this);
    }

    @Override
    public void setPresenter(ProjectListContract.ProjectListContractPresenter presenter) {
        mPresenter = (ProjectListPresenter) presenter;
    }

    @Override
    protected void initDataFromLocal() {

    }

    @Override
    public void onDestroy() {
        EventBus.getDefault().unregister(this);
        super.onDestroy();
    }

    @Override
    public void showProgressDialog() {
        progressDialog.show();
    }

    @Override
    public void closeProgressDialog() {
        progressDialog.hide();
    }

    @Override
    public void setListData(ProjectEntity projectEntity) {
        total = projectEntity.getData().getTotal();
        if (mNextPage == 1) {
            refreshLayout.setRefreshing(false);
            projectListAdapter.setNewData(projectEntity.getData().getList());
        } else {
            projectListAdapter.loadMoreComplete();
            projectListAdapter.addData(projectEntity.getData().getList());
        }
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
    }

    @Override
    public void onRefresh() {
        mNextPage = 1;
        loadDataFromServer(true);
    }

    @Override
    public void onLoadMoreRequested() {
        KLog.i("请求加载更多。。。");
        if (projectListAdapter.getData().size() < ONE_PAGE_SIZE || projectListAdapter.getData().size() >= total) {
            projectListAdapter.loadMoreEnd(true);
            return;
        }
        mNextPage ++;
        KLog.i("开始请求加载更多。。。");
        mPresenter.getProjectListFromServer(mType, mNextPage, ONE_PAGE_SIZE);
    }
}